package models;

import javax.persistence.EmbeddedId;
import javax.persistence.MappedSuperclass;

import jiyici.Constant.ModelColumn;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ObjectNode;

import play.db.ebean.Model;
import play.libs.Json;

@MappedSuperclass
public abstract class ServerBaseModel extends Model {

    private static final long serialVersionUID = -1491782683387616764L;
    
    @EmbeddedId
    public ServerModelId modelId;

    public long lastmodified;

    public boolean deleted = false;
    
    public void setId(long id) {
        if (modelId == null)
            modelId = new ServerModelId();
        modelId.id = id;
    }
    
    public long getId() {
        return modelId != null ? modelId.id : 0L;
    }
    
    public void setUserId(long userId) {
        if (modelId == null)
            modelId = new ServerModelId();
        modelId.userId = userId;
    }
    
    public long getUserId() {
        return modelId != null ? modelId.userId : 0L;
    }

    public ObjectNode toJson() {
        ObjectNode node = Json.newObject();
        node.put(ModelColumn.BASE_COLUMN_ID, modelId.id);
        node.put(ModelColumn.BASE_COLUMN_USERID, modelId.userId);
        node.put(ModelColumn.BASE_COLUMN_LASTMODIFIED, lastmodified);
        node.put(ModelColumn.BASE_COLUMN_DELETED, deleted);
        node.put(ModelColumn.BASE_COLUMN_DIRTY, false);
        return node;
    }

    public void fromJson(JsonNode json) {
        if (modelId == null)
            modelId = new ServerModelId();
        setId(json.findPath(ModelColumn.BASE_COLUMN_ID).getLongValue());
        setUserId(json.findPath(ModelColumn.BASE_COLUMN_USERID).getLongValue());
        lastmodified = json.findPath(ModelColumn.BASE_COLUMN_LASTMODIFIED).getLongValue();
        deleted = json.findPath(ModelColumn.BASE_COLUMN_DELETED).getBooleanValue();
    }
}
